import 'dart:io';

const host = "build/host/outputs/repo";

void main(List<String> args) async {
  if (args.isEmpty) {
    print("版本号是必填项: dart build_android_update.dart <version>");
    return;
  }

  var version = args[0];
  await run("./fvm build aar --build-number $version");

  print("构建完毕");

  final repos = findAllRepo(version);
  print(repos.join("\n"));

  upload(repos);
}

class Repo {
  String pom;
  String aar;

  @override
  String toString() {
    return "pom: $pom , aar: $aar ";
  }
}

List<Repo> findAllRepo(String version) {
  final hostDir = Directory(host);
  final files = hostDir.listSync(recursive: true);
  final dirs = files.where((test) {
    if (test is Directory) {
      final path = test.path.split("/");
      return path.last == version && test.path.contains("release");
    } else {
      return false;
    }
  }).toList();

  final repos = <Repo>[];

  for (final Directory dir in dirs) {
    final repo = Repo();
    repos.add(repo);
    for (final file in dir.listSync(recursive: true)) {
      if (file.path.endsWith("pom")) {
        repo.pom = file.absolute.path;
      } else if (file.path.endsWith("aar")) {
        repo.aar = file.absolute.path;
      }
    }
  }

  return repos;
}

Future<void> run(String command) async {
  print("run command: $command");

  final shellPath = "build/tmp.sh";
  final tmp = File(shellPath);
  tmp.writeAsStringSync(command);

  final process = await Process.start("sh", [shellPath]);

  stdout.addStream(process.stdout);
  stderr.addStream(process.stderr);

  await process.exitCode;

  tmp.deleteSync();
}

void upload(List<Repo> repos) async {
  for (final repo in repos) {
    final command =
        """mvn deploy:deploy-file -s mvn-config.xml -D packaging=aar -D file="${repo.aar}" -D pomFile="${repo.pom}" -D url=http://localhost:8099/repository/maven-releases/ -D repositoryId=releases""";
    await run(command);
  }
}
